#GPL3 +

import os
import json
import time
from modules import youtube

# "8eJEtnPUekY": {
#     "title": "Be Like That (From \"American Pie\" Soundtrack)",
#     "file": "/home/blenderdumbass/.matrix_music/8eJEtnPUekY.opus",
#     "duration": 237,
#     "timestamp": 1676962180,
#     "last_played": 1678008344
#     }

with open('stuff.json') as json_file: 
    stuff = json.load(json_file)

p = 0
for i in stuff["users"]:
    for song in stuff["users"][i]["history"]:
        fix = False
        try:
            info = stuff["songs"][song]

            if info.get("title") == song:
                print(song, "Title Is Link")
                p = p + 1
                fix = True

            elif type(info.get("title")) != str:
                print(song, "Title Type is Wrong")
                p = p + 1
                fix = True
            elif type(info.get("file")) != str:
                print(song, "File Type is Wrong")
                p = p + 1
                fix = True
            elif type(info.get("duration")) != int:
                print(song, "Duration Type is Wrong")
                p = p + 1
            elif type(info.get("timestamp")) != int:
                print(song, "Timestamp Type is Wrong")
                p = p + 1
                fix = True
                
        except:
            print(song, "Data Missing")
            p = p + 1
            fix = True

        if fix:
            print("Fixing:", song)
            videoId = song
            info = youtube.fetch_info(videoId)
            length = info.get("lengthSeconds", 9999999999999999)
            title = info.get("title", "")

            print("    Title:", title)
            print("    Length", length)
            
            stuff["songs"][videoId] = {"title":title,
                                       "file":None,
                                       "duration":length,
                                       "timestamp":int(time.time())}
            print()

print()
print(p, "problems in total.")


print("Saving!")
with open('stuff.json', 'w') as fp:
        json.dump(stuff, fp, indent=4)
